﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebTemplate.DAL.Repositories;
using WebTemplate.DAL.Entities;

namespace WebTemplate.ControlPanel.Account
{
    public partial class CourseDetails : System.Web.UI.Page
    {
        private int? ID
        {
            get
            {
                var idstr = this.Request.QueryString["id"];
                if (string.IsNullOrWhiteSpace(idstr))
                    return null;
                return int.Parse(idstr);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ID.HasValue)
                {
                    CoursesRepository repository = new CoursesRepository();
                    var courses = repository.Select(new CoursesSearchCriteria() { ID = this.ID.Value }).First();

                    this.Name.Text = courses.Name;
                    this.Description.Text = courses.Description;
                    this.PreReq.Text = courses.PreReq;
                    this.Dept.Text = courses.Department;
                }
            }

        }

        protected void SaveCourse_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                CoursesRepository repository = new CoursesRepository();
                Courses courses;
                if (ID.HasValue)
                {
                    courses = repository.Select(new CoursesSearchCriteria() { ID = this.ID.Value }).First();
                }
                else
                {
                    courses = new Courses();
                }

                courses.Name = Name.Text;
                courses.Description = Description.Text;
                courses.PreReq = PreReq.Text;
                courses.Department = Dept.Text;

                if(ID.HasValue)
                {
                    repository.Update(courses);
                }

                else
                {
                    repository.Insert(courses);
                }

                Response.Redirect("CoursesList.aspx");
            }

        }

        protected void CancelCourse_Click(object sender, EventArgs e)
        {
            Response.Redirect("CoursesList.aspx");
        }
    }
}